package com.dongdongshop.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //shiro的过滤器
        /*
        * anon : 无需认证直接放过
        * authc : 表示必须认证才能访问
        * perms : 表示当前的方法必须有XX个权限才能访问
        * logout : 退出登录过滤器
        * */
        Map<String,String> map = new LinkedHashMap<>();
        map.put("/shopLogin/login","anon");
        map.put("/shopLogin/tologin","anon");
        map.put("/registerController/register","anon");
        map.put("/registerController/getRegister","anon");
        map.put("/shopLogin/index","anon");
        map.put("/css/**","anon");
        map.put("/img/**","anon");
        map.put("/js/**","anon");
        map.put("/plugins/**","anon");
        map.put("/**","authc");
        shiroFilterFactoryBean.setLoginUrl("/shopLogin/login");
        //配置自定义错误页面
       shiroFilterFactoryBean.setUnauthorizedUrl("/shopLogin/error");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        return shiroFilterFactoryBean;
    }

    //创建安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginRealm loginRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //安全管理器需要关联登录和授权的这些功能
        securityManager.setRealm(loginRealm);
        return securityManager;
    }

    //创建自定义loginRealm
    @Bean
    public LoginRealm loginRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        LoginRealm loginRealm = new LoginRealm();
        loginRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return loginRealm;
    }

    //开启shiro的密码加密功能
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //设置加密方式
        matcher.setHashAlgorithmName("MD5");
        //加密(撒盐)的次数
        matcher.setHashIterations(10);
        //设置编码
        matcher.setStoredCredentialsHexEncoded(true);
        return matcher;
    }

    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }

}
